﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;


namespace JsonTool
{
    class JsonExporter
    {
        Dictionary<string, Dictionary<string, object>> mDic;

        public void ExeclToDict(DataTable sheet,int headerNum)
        {
            if (sheet.Columns.Count <= 0 || sheet.Rows.Count <= 0)
                return;
            mDic = new Dictionary<string, Dictionary<string, object>>();
            int firstRowData = headerNum - 1;
            for (int i = firstRowData; i < sheet.Rows.Count; i++)
            {
                DataRow row = sheet.Rows[i];
                string ID = row[sheet.Columns[0]].ToString();
                if (ID.Length == 0)
                    continue;
                var rowData = new Dictionary<string, object>();
                foreach (DataColumn column in sheet.Columns)
                {
                    string fieldName = column.ToString();
                    //若字段名第一个字符为'#',则该列不转换
                    if (fieldName[0] == '#')
                        continue;
                    object value = row[column];
                    //若为整数，转换为整型
                    if (value.GetType() == typeof(double))
                    {
                        double num = (double)value;
                        if ((int)num == num)
                            value = (int)num;
                    }
                    
                    if (!string.IsNullOrEmpty(fieldName))
                    {
                        rowData[fieldName] = value;
                    }
                }
                mDic[ID] = rowData;
            }
            Console.WriteLine("转换个数{0}", mDic.Count);
        }

        public void SaveToJson(string filePath,bool exportArray)
        {
            if (mDic.Count == 0)
                throw new Exception("数据为空");
            string json;
            if (exportArray)
            {
                List<Dictionary<string, object>> values = new List<Dictionary<string, object>>();
                foreach (var item in mDic.Values)
                {
                    values.Add(item);
                    Console.WriteLine(item);
                }
                
                json = JsonConvert.SerializeObject(values, Formatting.Indented);
            }
            else
            {
                json = JsonConvert.SerializeObject(mDic, Formatting.Indented);
            }
           
            FileStream fileStream = new FileStream(filePath,FileMode.Create,FileAccess.Write);
            TextWriter writer = new StreamWriter(fileStream);
            writer.Write(json);
            writer.Close();
            fileStream.Close();
            Console.WriteLine("保存成功");
        }
    }
}
